package labuda;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Leonid Bushuev from JetBrains
 */

public class RunLabuda
{

    public static void main(String[] args)
    {
        runTests(MiniTest.class);
    }


    private static void runTests(Class claß)
    {
        String claßName = claß.getName();
        System.out.println("##teamcity[testSuiteStarted name='" + claßName + "']");
        try {
            Method[] methods = claß.getDeclaredMethods();
            Object testClassInstance = claß.newInstance();
            for (int i = 0, methodsLength = methods.length; i < methodsLength; i++) {
                Method method = methods[i];
                String name = method.getName();
                if (name.length() > 4 && name.substring(0, 4).equals("test")) {
                    runTest(testClassInstance, method, name);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            System.out.println("##teamcity[testSuiteFinished name='" + claßName + "']");
        }
    }

    private static void runTest(Object testClassInstance, Method method, String name) throws IllegalAccessException, InvocationTargetException {
        sleep();
        System.out.flush();
        System.err.flush();
        System.out.println("##teamcity[testStarted name='" + name + "' captureStandardOutput='true']");

        try {
            method.invoke(testClassInstance, new Object[0]);
        }
        catch (InvocationTargetException ite) {
            Throwable e = ite.getTargetException();
            e.printStackTrace();
            System.err.flush();
            System.out.print("##teamcity[testFailed type='exception' name='" + name + "' message='" + e.toString() + "']");
            sleep();
        }
        catch (Throwable e) {
            e.printStackTrace();
            System.err.flush();
            System.out.print("##teamcity[testFailed type='exception' name='" + name + "' message='" + e.getMessage() + "'");
            sleep();
        }

        System.out.flush();
        System.err.flush();
        System.out.println("##teamcity[testFinished name='" + name + "']");
        System.out.flush();
        sleep();
    }

    private static void sleep() {
        try {
            Thread.sleep(30);
        } catch (InterruptedException e) {
        }
    }

}
